<template>
	<view class="change-password-container">
		<view class="nav-bar">
			<view class="nav-left">
				<uni-icons type="arrowleft" size="24px" color="#333" @click="handleBack"></uni-icons>
			</view>
			<view class="nav-title">修改密码</view>
		</view>

		<view class="form-container">
			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999"></uni-icons>
				<input class="input" :type="showOldPassword ? 'text' : 'password'" placeholder="请输入旧密码"
					v-model="oldPassword" />
				<uni-icons :type="showOldPassword ? 'eye' : 'eye-slash'" size="20" color="#999"
					@click="showOldPassword = !showOldPassword"></uni-icons>
			</view>

			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999"></uni-icons>
				<input class="input" :type="showNewPassword ? 'text' : 'password'" placeholder="请输入新密码"
					v-model="newPassword" />
				<uni-icons :type="showNewPassword ? 'eye' : 'eye-slash'" size="20" color="#999"
					@click="showNewPassword = !showNewPassword"></uni-icons>
			</view>

			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999"></uni-icons>
				<input class="input" :type="showConfirmPassword ? 'text' : 'password'" placeholder="请确认新密码"
					v-model="confirmPassword" />
				<uni-icons :type="showConfirmPassword ? 'eye' : 'eye-slash'" size="20" color="#999"
					@click="showConfirmPassword = !showConfirmPassword"></uni-icons>
			</view>

			<view v-if="errorMessage" class="error-message">{{ errorMessage }}</view>

			<button class="submit-btn" @click="handleSubmit">确认修改</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';

	const oldPassword = ref('');
	const newPassword = ref('');
	const confirmPassword = ref('');
	const showOldPassword = ref(false);
	const showNewPassword = ref(false);
	const showConfirmPassword = ref(false);
	const userId = ref(null);
	const isLoading = ref(false);
	const errorMessage = ref('');

	// 从sessionStorage获取用户ID
	onMounted(() => {
		try {
			const userinfoStr = sessionStorage.getItem('userinfo');
			if (userinfoStr) {
				const userinfo = JSON.parse(userinfoStr);
				userId.value = userinfo.id;
				console.log('获取到的用户信息:', userinfo);
				console.log('当前用户ID:', userId.value);
			} else {
				console.error('未找到用户信息，请先登录');
				errorMessage.value = '请先登录';
				// 可以跳转到登录页
				// uni.redirectTo({ url: '/pages/login/login' });
			}
		} catch (e) {
			console.error('解析用户信息失败:', e);
			errorMessage.value = '用户信息错误';
		}
	});
	const canSubmit = computed(() => {
		return (
			oldPassword.value.length >= 6 &&
			newPassword.value.length >= 6 &&
			newPassword.value === confirmPassword.value &&
			newPassword.value !== oldPassword.value &&
			userId.value
		);
	});

	const handleSubmit = async () => {
		if (!canSubmit.value) return;

		isLoading.value = true;
		errorMessage.value = '';

		try {
			uni.showLoading({
				title: '修改中...'
			});

			// 1. 获取当前用户数据
			const res = await uni.request({
				url: `http://localhost:3000/users/${userId.value}`,
				method: 'GET'
			});

			const userData = res[1].data;

			// 2. 验证旧密码
			if (userData.password !== oldPassword.value) {
				throw new Error('旧密码不正确');
			}

			// 3. 更新密码
			await uni.request({
				url: `http://localhost:3000/users/${userId.value}`,
				method: 'PATCH',
				data: {
					password: newPassword.value
				},
				header: {
					'Content-Type': 'application/json'
				}
			});

			uni.showToast({
				title: '密码修改成功',
				icon: 'success',
				success: () => {
					oldPassword.value = '';
					newPassword.value = '';
					confirmPassword.value = '';
					setTimeout(() => uni.navigateBack(), 1500);
				}
			});

		} catch (error) {
			console.error('修改密码失败:', error);
			errorMessage.value = error.message || '修改密码失败';
			uni.showToast({
				title: errorMessage.value,
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
			uni.hideLoading();
		}
	};
</script>

<style>
	.change-password-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #f5f5f5;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		padding: 0 32rpx;
		background-color: #fff;
		position: relative;
	}

	.nav-left {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 18px;
		font-weight: 500;
		color: #333;
	}

	.form-container {
		padding: 40rpx 32rpx;
	}

	.input-group {
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 20rpx;
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 10rpx;
		border: 1px solid #eee;
	}

	.input {
		flex: 1;
		height: 100%;
		padding: 0 20rpx;
		font-size: 16px;
	}

	.submit-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 16px;
		color: #fff;
		background-color: #4CAF50;
		border-radius: 10rpx;
		margin-top: 60rpx;
	}

	.submit-btn[disabled] {
		background-color: #ccc;
	}

	.error-message {
		color: #ff4d4f;
		font-size: 14px;
		text-align: center;
		margin-top: 10px;
		height: 20px;
	}
</style>